﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc;
using System.Web.WebPages;
using Sharp.Portal.Owin;
using System.Diagnostics;

namespace Sharp.Portal.Mvc
{
    [DebuggerStepThrough]
    public class SharpWebViewPage : WebViewPage
    {
        public override void InitHelpers()
        {
            this.Ajax = null;
            this.Html = null;
            this.Url = new SharpUrlHelper(this.ViewContext.RequestContext);
        }
        public override void Execute()
        {
            throw new NotImplementedException();
        }

        protected override void ConfigurePage(WebPageBase parentPage)
        {
            base.ConfigurePage(parentPage);
        }
         
    }
    [DebuggerStepThrough]
    public class SharpWebViewPage<TModel> : WebViewPage<TModel>
    {
        protected SharpWebViewPage() : base()
        {

        }

        public override void InitHelpers()
        {
            this.Url = new SharpUrlHelper(this.ViewContext.RequestContext);
            this.Ajax = new AjaxHelper<TModel>(base.ViewContext, this);
            this.Html = new HtmlHelper<TModel>(base.ViewContext, this);
        }

        protected string ModuleCode { get; set; }

        /// <summary>
        /// 是否启用字段权限功能
        /// </summary>
        public bool? EnableFieldPermissions { get; set; }

        public string SystemCode { get; set; }

        private void InitPermissionConfig()
        {
            if (EnableFieldPermissions != null) return;

            if (this.Model == null) return;

            this.ModuleCode = this.Model.GetType().GetCustomAttributes(typeof(ModuleCodeAttribute), true)
                .OfType<ModuleCodeAttribute>().FirstOrDefault()?.Code;
            if (ModuleCode.IsNullOrEmpty())
            {
                EnableFieldPermissions = false;
            }
            else
            {
                //全局权限是否启用了字段权限
                EnableFieldPermissions =
                    Platform.AllPermission().Any(x => x.Code.StartsWith(ModuleCode + "_DataList_"));
            }
        }
        /// <summary>
        /// 检查
        /// </summary>
        /// <param name="field"></param>
        /// <returns></returns>
        public bool CheckFieldPermission(string field)
        {
            if (EnableFieldPermissions == null || !EnableFieldPermissions.Value)
                return true;

            return SharpUserManager.Current.Permissions.Any(x => x.Code.Equals($"{this.ModuleCode}_DataList_{field}", StringComparison.CurrentCultureIgnoreCase));
        }
        public override void Execute()
        {
            throw new NotImplementedException();
        }

        protected override void ConfigurePage(WebPageBase parentPage)
        {
            base.ConfigurePage(parentPage);
            InitPermissionConfig();
        }

    }
}
